package com.gwz.wxtime.chessboard.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gwz.wxtime.chessboard.entity.*;
import com.gwz.wxtime.chessboard.util.PukeUtil;
import com.gwz.wxtime.core.consts.RedisKeyConst;
import com.gwz.wxtime.core.entity.base.BaseDTO;
import com.gwz.wxtime.core.entity.wx.GroupReceiveMessage;
import com.gwz.wxtime.core.service.BaseService;
import com.gwz.wxtime.core.util.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
@Order(2)
public class WuZiQiService implements BaseService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public boolean handGroupReceivedMessage(BaseDTO<BaseDTO<GroupReceiveMessage>> dto) throws InterruptedException {
        log.info("五子棋请求");
        BaseDTO<GroupReceiveMessage> data = dto.getData();

        if (data.getData().getMsg().equals("五子棋")) {
            douDiZhuInstruction(data.getData());
            return true;
        }

        if (data.getData().getMsg().startsWith("加入房间#")) {
            return findRoom(data.getData());
        }


        PlayRedis playInfo = getPlayInfo(data.getData().getFromWxid(), data.getData().getFinalFromWxid());
        if (playInfo == null) {
            //WxUtil.sendMessage(data.getData().getFromWxid(), WxUtil.at(data.getData().getFinalFromWxid()) + " ");
            return false;
        }


        if (data.getData().getMsg().startsWith("创建房间#")) {
            createRoom(data.getData());
            return true;
        } else if (data.getData().getMsg().startsWith("加入房间#")) {
            joinRoom(data.getData());
            return true;
        } else if (data.getData().getMsg().equals("退出房间")) {
            exitRoom(data.getData());
            return true;
        } else if (data.getData().getMsg().startsWith("设置显示#")) {
            settingShow(data.getData());
            return true;
        } else if (data.getData().getMsg().equals("开始")) {
            startGame(data.getData());
            return true;
        } else if (data.getData().getMsg().equals("悔棋")) {
            regretChess(data.getData());
            return true;
        } else if (data.getData().getMsg().equals("认输")) {
            surrender(data.getData());
            return true;
        } else if (data.getData().getMsg().startsWith("出#")) {
            playChess(data.getData());
            return true;
        } else if (ReUtil.isMatch("[0-9]{1,2}[\\s,]{0,1}[a-zA-Z]{1}", data.getData().getMsg())) {
            playChessRe(data.getData());
            return true;
        }
        return false;
    }


    private void douDiZhuInstruction(GroupReceiveMessage data) {

        PlayRedis playRedis = new PlayRedis();
        playRedis.setWxId(data.getFinalFromWxid());
        playRedis.setPositionWxid(data.getFromWxid());
        String redisKey = StrUtil.format(RedisKeyConst.WuZiQiPlayInfo, data.getFinalFromWxid(), data.getFromWxid());
        if (Boolean.FALSE.equals(redisTemplate.hasKey(redisKey))) {
            redisTemplate.opsForValue().set(redisKey, playRedis, 36, TimeUnit.HOURS);
        }
        String douDiZhuRedisKey = StrUtil.format(RedisKeyConst.DouDiZhuPlayInfo, data.getFinalFromWxid(), data.getFromWxid());
        redisTemplate.delete(douDiZhuRedisKey);

        WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + " 五子棋 [玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰]\n"
                + "创建房间:  创建房间#房间号\n"
                + "加入房间:   加入房间#房间号\n"
                + "退出房间:   退出房间\n"
                + "开始指令:   开始\n"
                + "悔棋指令:   悔棋\n"
                + "认输指令:   认输\n"
                + "设置五子棋文字显示:   设置显示#文字 / 设置显示#图片\n"
                + "下棋:  8h\n"
                + "tips: 开始需要等到房间人数够");

    }


    private void createRoom(GroupReceiveMessage data) {
        try {
            String msg = data.getMsg();
            String roomNo = msg.split("#")[1];
            String redisKey = StrUtil.format(RedisKeyConst.WuZiQiRoomInfo, data.getFromWxid(), roomNo);

            if (Boolean.TRUE.equals(redisTemplate.hasKey(redisKey))) {
                WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间已存在");
                return;
            }

            String playRedisKey = StrUtil.format(RedisKeyConst.WuZiQiPlayInfo, data.getFinalFromWxid(), data.getFromWxid());
            PlayRedis playRedis = (PlayRedis) redisTemplate.opsForValue().get(playRedisKey);

            // 之前有房间置空
            if (StrUtil.isNotEmpty(playRedis.getRoomNo())) {
                String oldRedisRoomKey = StrUtil.format(RedisKeyConst.WuZiQiRoomInfo, data.getFromWxid(), playRedis.getRoomNo());
                RoomRedis roomRedis = (RoomRedis) redisTemplate.opsForValue().get(oldRedisRoomKey);
                if (roomRedis.getWxId1().equals(playRedis.getWxId())) roomRedis.setWxId1(null);
                else if (roomRedis.getWxId2().equals(playRedis.getWxId())) roomRedis.setWxId2(null);
                else if (roomRedis.getWxId3().equals(playRedis.getWxId())) roomRedis.setWxId3(null);

                redisTemplate.opsForValue().set(oldRedisRoomKey, roomRedis, 1, TimeUnit.HOURS);
            }

            RoomRedis roomRedis = new RoomRedis();
            roomRedis.setWxId1(data.getFinalFromWxid());
            roomRedis.setPositionWxId(data.getFromWxid());
            roomRedis.setStatus(1);
            roomRedis.setChessShowType(2);
            roomRedis.setRoomNo(roomNo);

            redisTemplate.opsForValue().set(redisKey, roomRedis, 1, TimeUnit.HOURS);

            playRedis.setRoomNo(roomNo);
            redisTemplate.opsForValue().set(playRedisKey, playRedis, 1, TimeUnit.HOURS);

            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "创建房间成功");

        } catch (Exception e) {
            e.printStackTrace();
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "格式错误");
        }
    }


    private boolean findRoom(GroupReceiveMessage data) {
        String msg = data.getMsg();
        String roomNo = msg.split("#")[1];


        String redisKey = StrUtil.format(RedisKeyConst.WuZiQiRoomInfo, data.getFromWxid(), roomNo);
        if (Boolean.TRUE.equals(redisTemplate.hasKey(redisKey))) {
            douDiZhuInstruction(data);
            joinRoom(data);
            return true;
        }
        return false;
    }


    private void joinRoom(GroupReceiveMessage data) {

        try {
            String msg = data.getMsg();
            String roomNo = msg.split("#")[1];


            String redisKey = StrUtil.format(RedisKeyConst.WuZiQiRoomInfo, data.getFromWxid(), roomNo);

            String playRedisKey = StrUtil.format(RedisKeyConst.WuZiQiPlayInfo, data.getFinalFromWxid(), data.getFromWxid());
            PlayRedis playRedis = (PlayRedis) redisTemplate.opsForValue().get(playRedisKey);

            if (StrUtil.isNotEmpty(playRedis.getRoomNo())) {
                WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "请先退出当前房间");
                return;
            }

            if (Boolean.FALSE.equals(redisTemplate.hasKey(redisKey))) {
                WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "未找到房间");
                return;
            }

            RoomRedis roomRedis = (RoomRedis) redisTemplate.opsForValue().get(redisKey);
            if (StrUtil.isEmpty(roomRedis.getWxId1())) {
                roomRedis.setWxId1(playRedis.getWxId());
            } else if (StrUtil.isEmpty(roomRedis.getWxId2())) {
                roomRedis.setWxId2(playRedis.getWxId());
            } else {
                WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间已满员");
                return;
            }

            redisTemplate.opsForValue().set(redisKey, roomRedis, 1, TimeUnit.HOURS);

            playRedis.setRoomNo(roomNo);
            redisTemplate.opsForValue().set(playRedisKey, playRedis, 1, TimeUnit.HOURS);


            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "加入房间成功");


            /*if (StrUtil.isNotEmpty(roomRedis.getWxId1()) && StrUtil.isNotEmpty(roomRedis.getWxId2())) {
                startGame(roomRedis);
            }*/


        } catch (Exception e) {
            e.printStackTrace();
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "格式错误");
        }
    }





    private void exitRoom(GroupReceiveMessage data) {
        try {
            String msg = data.getMsg();


            String playRedisKey = StrUtil.format(RedisKeyConst.WuZiQiPlayInfo, data.getFinalFromWxid(), data.getFromWxid());
            PlayRedis playRedis = (PlayRedis) redisTemplate.opsForValue().get(playRedisKey);

            String roomNo = playRedis.getRoomNo();
            if (StrUtil.isEmpty(playRedis.getRoomNo())) {
                WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "未找到房间");
                return;
            }

            String redisKey = StrUtil.format(RedisKeyConst.WuZiQiRoomInfo, data.getFromWxid(), roomNo);
            RoomRedis roomRedis = (RoomRedis) redisTemplate.opsForValue().get(redisKey);

            if (playRedis.getWxId().equals(roomRedis.getWxId1())) {
                roomRedis.setWxId1(null);
            } else if (playRedis.getWxId().equals(roomRedis.getWxId2())) {
                roomRedis.setWxId2(null);
            } else if (playRedis.getWxId().equals(roomRedis.getWxId3())) {
                roomRedis.setWxId3(null);
            } else {
                WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "不在这个房间");
                return;
            }
            roomRedis.setStatus(1);
            redisTemplate.opsForValue().set(redisKey, roomRedis, 1, TimeUnit.HOURS);

            playRedis.setRoomNo(null);
            redisTemplate.opsForValue().set(playRedisKey, playRedis, 1, TimeUnit.HOURS);


            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "退出房间成功 房间游戏自动退出");

        } catch (Exception e) {
            e.printStackTrace();
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "格式错误");
        }
    }


    private void startGame(GroupReceiveMessage data) {


        PlayRedis playInfo = getPlayInfo(data.getFromWxid(), data.getFinalFromWxid());
        if (StrUtil.isEmpty(playInfo.getRoomNo())) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "请先加入 或者 创建房间");
            return;
        }
        RoomRedis roomRedis = getRoomInfo(data.getFromWxid(), playInfo.getRoomNo());
        if (roomRedis == null) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间已销毁,请重新加入 或者 创建房间");
            playInfo.setRoomNo(null);
            setPlayInfo(playInfo);
            return;
        }
        if (roomRedis.getStatus() != 1) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间状态错误");
            return;
        }
        if (StrUtil.isEmpty(roomRedis.getWxId1()) || StrUtil.isEmpty(roomRedis.getWxId2())) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "需要两人才可以开始游戏");
            return;
        }
        List<Puke> pukes = PukeUtil.initPuke();
        Collections.shuffle(pukes);

        //取出二位玩家
        PlayRedis playInfo1 = getPlayInfo(roomRedis.getPositionWxId(), roomRedis.getWxId1());
        PlayRedis playInfo2 = getPlayInfo(roomRedis.getPositionWxId(), roomRedis.getWxId2());
        List<PlayRedis> players = new ArrayList<>();
        players.add(playInfo1);
        players.add(playInfo2);

        PlayRedis blackRedis = RandomUtil.randomEle(players);
        roomRedis.setBlackChessWxId(blackRedis.getWxId());
        roomRedis.setGoChessWxId(blackRedis.getWxId());


        List<List<ChessData>> chessDataList = new ArrayList<>();

        for (int i = 0; i < 15; i++) {
            List<ChessData> chessDatas = new ArrayList<>(15);

            for (int j = 0; j < 15; j++) {
                ChessData chessData = new ChessData();
                chessData.setType(0);
                chessDatas.add(chessData);
            }

            chessDataList.add(chessDatas);
        }
        roomRedis.setStatus(2);
        roomRedis.setChessLinkList(new LinkedList<>());

        roomRedis.setChessDataList(chessDataList);
        if (roomRedis.getChessShowType() == 1) {
            WxUtil.sendMessage(roomRedis.getPositionWxId(),
                    transTxt(chessDataList));
        } else {
            String path = transImg(chessDataList, roomRedis.getRoomNo(), 0, 0, null, null);
            WxUtil.sendImage(roomRedis.getPositionWxId(), path);
        }
        WxUtil.sendMessage(roomRedis.getPositionWxId(), WxUtil.at(blackRedis.getWxId()) + " 执黑棋先行  下棋指令: 8h");

        // 设置房间信息
        setRoomInfo(roomRedis);
    }


    public void playChess(GroupReceiveMessage data) {
        PlayRedis playInfo = getPlayInfo(data.getFromWxid(), data.getFinalFromWxid());
        if (StrUtil.isEmpty(playInfo.getRoomNo())) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "请先加入 或者 创建房间");
            return;
        }
        RoomRedis roomInfo = getRoomInfo(data.getFromWxid(), playInfo.getRoomNo());
        if (roomInfo == null) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间已销毁,请重新加入 或者 创建房间");
            playInfo.setRoomNo(null);
            setPlayInfo(playInfo);
            return;
        }
        if (roomInfo.getStatus() != 2) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间状态错误");
            return;
        }
        if (!roomInfo.getGoChessWxId().equals(data.getFinalFromWxid())) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "不该你下");
            return;
        }
        try {
            String msg = data.getMsg();
            ArrayList<String> cardListStr = CollectionUtil.newArrayList(msg.split("#"));
            cardListStr.remove(0);
            cardListStr = CollectionUtil.newArrayList(cardListStr.get(0).split(" "));
            List<Integer> position = transAxis(cardListStr);
            ChessData chessData = roomInfo.getChessDataList().get(position.get(0)).get(position.get(1));
            if (chessData.getType() != 0) {
                WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "已经有棋子了");
                return;
            }

            if (roomInfo.getBlackChessWxId().equals(playInfo.getWxId())) {
                chessData.setType(1);
            } else {
                chessData.setType(2);
            }
            roomInfo.setGoChessWxId(nextWxId(roomInfo, roomInfo.getGoChessWxId()));
            roomInfo.getChessLinkList().push(position);

            int isWin = checkWin(roomInfo.getChessDataList(), position);


            if (roomInfo.getChessShowType() == 1) {
                WxUtil.sendMessage(data.getFromWxid(), transTxt(roomInfo.getChessDataList()));

            } else {
                String path = transImg(roomInfo.getChessDataList(), roomInfo.getRoomNo(), isWin, chessData.getType(), position.get(0), position.get(1));
                WxUtil.sendImage(roomInfo.getPositionWxId(), path);
            }


            if (isWin == 2) {
                WxUtil.sendMessage(data.getFromWxid(), "[玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰]恭喜" + WxUtil.at(data.getFinalFromWxid()) + " 执" + (chessData.getType() == 1 ? "黑" : "白") + "胜利 [玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰]");
                roomInfo.setStatus(1);
                //startGame(roomInfo);
            } else {
                WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(roomInfo.getGoChessWxId()) + " 该你下了");
            }
            setRoomInfo(roomInfo);

        } catch (Exception e) {
            e.printStackTrace();
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "格式错误");
        }
    }

    private void playChessRe(GroupReceiveMessage data) {
        String msg = "出#";
        String x = "";
        String y = "";
        if (data.getMsg().indexOf(",") > 0) {
            x = data.getMsg().split(",")[0];
            y = data.getMsg().split(",")[1];
        } else if (data.getMsg().indexOf(" ") > 0) {
            x = data.getMsg().split(" ")[0];
            y = data.getMsg().split(" ")[1];
        } else {
            x = String.valueOf(ReUtil.getFirstNumber(data.getMsg()));
            y = data.getMsg().replace(x, "");
        }
        data.setMsg(msg + x + " " + y);
        playChess(data);
    }


    private void regretChess(GroupReceiveMessage data) throws InterruptedException {
        PlayRedis playInfo = getPlayInfo(data.getFromWxid(), data.getFinalFromWxid());
        if (StrUtil.isEmpty(playInfo.getRoomNo())) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "请先加入 或者 创建房间");
            return;
        }
        RoomRedis roomInfo = getRoomInfo(data.getFromWxid(), playInfo.getRoomNo());
        if (roomInfo == null) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间已销毁,请重新加入 或者 创建房间");
            playInfo.setRoomNo(null);
            setPlayInfo(playInfo);
            return;
        }
        if (roomInfo.getStatus() != 2) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间状态错误");
            return;
        }
        if (roomInfo.getGoChessWxId().equals(data.getFinalFromWxid())) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "不能悔棋");
            return;
        }
        List<Integer> position = roomInfo.getChessLinkList().pop();
        ChessData chessData = roomInfo.getChessDataList().get(position.get(0)).get(position.get(1));
        chessData.setType(0);
        roomInfo.setGoChessWxId(nextWxId(roomInfo, roomInfo.getGoChessWxId()));

        WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(roomInfo.getGoChessWxId()) + "  悔棋");
        Thread.sleep(100);
        if (roomInfo.getChessShowType() == 1) {
            WxUtil.sendMessage(data.getFromWxid(), transTxt(roomInfo.getChessDataList()));

        } else {
            String path = transImg(roomInfo.getChessDataList(), roomInfo.getRoomNo(), 1, chessData.getType(), roomInfo.getChessLinkList().getFirst().get(0), roomInfo.getChessLinkList().getFirst().get(1));
            WxUtil.sendImage(roomInfo.getPositionWxId(), path);
        }
        setRoomInfo(roomInfo);
        WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(roomInfo.getGoChessWxId()) + " 该你下了");
    }

    private void surrender(GroupReceiveMessage data) throws InterruptedException {
        PlayRedis playInfo = getPlayInfo(data.getFromWxid(), data.getFinalFromWxid());
        if (StrUtil.isEmpty(playInfo.getRoomNo())) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "请先加入 或者 创建房间");
            return;
        }
        RoomRedis roomInfo = getRoomInfo(data.getFromWxid(), playInfo.getRoomNo());
        if (roomInfo == null) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间已销毁,请重新加入 或者 创建房间");
            playInfo.setRoomNo(null);
            setPlayInfo(playInfo);
            return;
        }
        if (roomInfo.getStatus() != 2) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间状态错误");
            return;
        }

        String nextWxId = nextWxId(roomInfo, data.getFinalFromWxid());

        WxUtil.sendMessage(data.getFromWxid(), "[玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰]恭喜" + WxUtil.at(nextWxId) + " 执" + (roomInfo.getBlackChessWxId().equals(nextWxId) ? "黑" : "白") + "胜利 [玫瑰][玫瑰][玫瑰][玫瑰][玫瑰][玫瑰]");
        roomInfo.setStatus(1);
        setRoomInfo(roomInfo);
    }

    private void settingShow(GroupReceiveMessage data) {
        PlayRedis playInfo = getPlayInfo(data.getFromWxid(), data.getFinalFromWxid());
        if (StrUtil.isEmpty(playInfo.getRoomNo())) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "请先加入 或者 创建房间");
            return;
        }
        RoomRedis roomInfo = getRoomInfo(data.getFromWxid(), playInfo.getRoomNo());
        if (roomInfo == null) {
            WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "房间已销毁,请重新加入 或者 创建房间");
            playInfo.setRoomNo(null);
            setPlayInfo(playInfo);
            return;
        }
        if (data.getMsg().endsWith("文字")) {
            roomInfo.setChessShowType(1);
        } else if (data.getMsg().endsWith("图片")) {
            roomInfo.setChessShowType(2);
        }
        WxUtil.sendMessage(data.getFromWxid(), WxUtil.at(data.getFinalFromWxid()) + "设置成功");

        setRoomInfo(roomInfo);
    }

    /**
     * 查看位置是否胜利 1: 不分胜负 2 胜
     *
     * @param chessDataList
     * @param position
     * @return
     */
    public int checkWin(List<List<ChessData>> chessDataList, List<Integer> position) {
        Integer x = position.get(0);
        Integer y = position.get(1);
        ChessData chessData = chessDataList.get(x).get(y);

        // 左右
        int XContinuousCount = 0;
        // 上下连续
        int yContinuousCount = 0;
        // 左上下连续
        int leftXYContinuousCount = 0;
        // 右上下连续
        int rightXYContinuousCount = 0;

        // 判断上

        for (int i = 1; i < 6; i++) {
            if (x - i >= 0) {
                ChessData continuousChessData = chessDataList.get(x - i).get(y);
                if (chessData.getType() != continuousChessData.getType()) {
                    break;
                }
                yContinuousCount++;
                if (yContinuousCount == 4) {
                    return 2;
                }

            }
        }

        // 判断下
        for (int i = 1; i < 6; i++) {
            if (x + i < 15) {
                ChessData continuousChessData = chessDataList.get(x + i).get(y);
                if (chessData.getType() != continuousChessData.getType()) {
                    break;
                }
                yContinuousCount++;
                if (yContinuousCount == 4) {
                    return 2;
                }

            }
        }

        // 判断左
        for (int i = 1; i < 6; i++) {
            if (y - i >= 0) {
                ChessData continuousChessData = chessDataList.get(x).get(y - i);
                if (chessData.getType() != continuousChessData.getType()) {
                    break;
                }
                XContinuousCount++;
                if (XContinuousCount == 4) {
                    return 2;
                }

            }
        }
        // 判断右
        for (int i = 1; i < 6; i++) {
            if (y + i < 15) {
                ChessData continuousChessData = chessDataList.get(x).get(y + i);
                if (chessData.getType() != continuousChessData.getType()) {
                    break;
                }
                XContinuousCount++;
                if (XContinuousCount == 4) {
                    return 2;
                }

            }
        }

        // 判断左上
        for (int i = 1; i < 6; i++) {
            int newx = x - i;
            int newy = y - i;
            if (newx >= 0 && newy >= 0) {
                ChessData continuousChessData = chessDataList.get(newx).get(newy);
                if (chessData.getType() != continuousChessData.getType()) {
                    break;
                }
                leftXYContinuousCount++;
                if (leftXYContinuousCount == 4) {
                    return 2;
                }

            }
        }

        // 判断左下
        for (int i = 1; i < 6; i++) {
            int newx = x + i;
            int newy = y - i;
            if (newx < 15 && newy >= 0) {
                ChessData continuousChessData = chessDataList.get(newx).get(newy);
                if (chessData.getType() != continuousChessData.getType()) {
                    break;
                }
                rightXYContinuousCount++;

                if (rightXYContinuousCount == 4) {
                    return 2;
                }

            }
        }

        // 判断右上
        for (int i = 1; i < 6; i++) {
            int newx = x - i;
            int newy = y + i;
            if (newx >= 0 && newy < 15) {
                ChessData continuousChessData = chessDataList.get(newx).get(newy);
                if (chessData.getType() != continuousChessData.getType()) {
                    break;
                }
                rightXYContinuousCount++;
                if (rightXYContinuousCount == 4) {
                    return 2;
                }

            }
        }

        // 判断右下
        for (int i = 1; i < 6; i++) {
            int newx = x + i;
            int newy = y + i;
            if (newx < 15 && newy < 15) {
                ChessData continuousChessData = chessDataList.get(newx).get(newy);
                if (chessData.getType() != continuousChessData.getType()) {
                    break;
                }
                leftXYContinuousCount++;

                if (leftXYContinuousCount == 4) {
                    return 2;
                }

            }
        }

        return 1;
    }

    private String transTxt(List<List<ChessData>> chessDataList) {
        String space = "  ";
        StringBuilder result = new StringBuilder(space + space);
        for (int i = 0; i < 15; i++) {
            result.append(i + 1);
            result.append(space);
        }
        result.append("\n");
        char leftAxis = 65;
        for (int x = 0; x < 15; x++) {
            List<ChessData> chessDataX = chessDataList.get(x);
            result.append(leftAxis);
            result.append(space);
            leftAxis++;
            for (int y = 0; y < 15; y++) {
                ChessData chessDataXY = chessDataX.get(y);
                if (chessDataXY.getType() == 1) {
                    result.append("●");
                } else if (chessDataXY.getType() == 2) {
                    result.append("o");
                }
                result.append(space);
                if (y > 8) {
                    result.append(" ");
                }
            }
            result.append("\n");
        }
        return result.toString();
    }


    /**
     * @param chessDataList
     * @param roomNo
     * @param isWin         1不胜不负 2 胜
     * @param win           1黑胜 2 白胜
     * @return
     */
    public String transImg(List<List<ChessData>> chessDataList, String roomNo, int isWin, int win, Integer lastX, Integer lastY) {
        // 单元格宽度
        BufferedImage image = new BufferedImage(313, 313, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
//        graphics.setColor(new Color(249, 214, 91));
//        graphics.fillRect(0, 0, 185, 185);
        graphics.setColor(Color.black);

        Font fonttile = new Font("微软雅黑", Font.ROMAN_BASELINE, 7);
        graphics.setFont(fonttile);

        Image backageImage = new ImageIcon(ResourceUtil.getResource("wuZiQi.png")).getImage();
        graphics.drawImage(backageImage, 0, 0, null);


        // 棋子
        for (int x = 0; x < 15; x++) {
            List<ChessData> chessDataX = chessDataList.get(x);

            for (int y = 0; y < 15; y++) {
                ChessData chessDataXY = chessDataX.get(y);
                if (chessDataXY.getType() != 0) {
                    int chessX = (20 * y) + 16 - 7;
                    int chessY = (20 * x) + 16 - 7;
                    if (chessDataXY.getType() == 1) {
                        graphics.setColor(Color.black);
                    } else {
                        graphics.setColor(Color.white);
                    }
                    graphics.fillArc(chessX, chessY, 15, 15, 0, -360);
                }
            }
        }

        if (lastX != null && lastY != null) {
            int chessX = (20 * lastY) + 16 - 3;
            int chessY = (20 * lastX) + 16 - 3;
            graphics.setColor(Color.red);
            graphics.fillArc(chessX, chessY, 8, 8, 0, -360);
        }


        if (isWin == 2) {
            if (win == 1) {
                graphics.setColor(Color.black);
            } else {
                graphics.setColor(Color.white);
            }
            graphics.fillArc(100, 100, 30, 30, 0, -360);
            graphics.setColor(Color.red);
            graphics.setFont(new Font("微软雅黑", Font.BOLD, 30));
            graphics.drawString("WIN", 140, 125);
        }
        graphics.dispose();

        //画顶部的横线
        // graphics.drawLine(0, 1, 120, 1);


        try {
            String path = "C:\\Users\\Administrator\\Desktop\\data" + File.separator + roomNo  + "wzq.jpg";


            log.info("加载path:{}" + path);
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }


            FileOutputStream fos = new FileOutputStream(path);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            ImageIO.write(image, "jpg", fos);
            bos.close();
            return path;

        } catch (Exception e) {
            log.info("错误", e);
        }
        return null;
    }


    private List<Integer> transAxis(List<String> chessPosition) {
        String x = chessPosition.get(0);
        String y = chessPosition.get(1);
        Integer newX = 15 - Integer.parseInt(x);
        Integer newY = y.charAt(0) > 79 ? y.charAt(0) - 97 : y.charAt(0) - 65;
        return List.of(newX, newY);
    }

    /**
     * 获取下一个微信id
     *
     * @param roomRedis
     * @param wxId
     * @return
     */
    private String nextWxId(RoomRedis roomRedis, String wxId) {
        if (roomRedis.getWxId1().equals(wxId)) return roomRedis.getWxId2();
        if (roomRedis.getWxId2().equals(wxId)) return roomRedis.getWxId1();
        return null;
    }


    private void setRoomInfo(RoomRedis roomRedis) {
        String redisKey = StrUtil.format(RedisKeyConst.WuZiQiRoomInfo, roomRedis.getPositionWxId(), roomRedis.getRoomNo());
        redisTemplate.opsForValue().set(redisKey, roomRedis, 1, TimeUnit.HOURS);
    }

    private void setPlayInfo(PlayRedis playRedis) {
        String playRedisKey = StrUtil.format(RedisKeyConst.WuZiQiPlayInfo, playRedis.getWxId(), playRedis.getPositionWxid());
        redisTemplate.opsForValue().set(playRedisKey, playRedis, 1, TimeUnit.HOURS);
    }

    public RoomRedis getRoomInfo(String positionWxId, String roomNo) {
        String redisKey = StrUtil.format(RedisKeyConst.WuZiQiRoomInfo, positionWxId, roomNo);
        return (RoomRedis) redisTemplate.opsForValue().get(redisKey);
    }

    private PlayRedis getPlayInfo(String positionWxId, String wxId) {
        String playRedisKey = StrUtil.format(RedisKeyConst.WuZiQiPlayInfo, wxId, positionWxId);
        return (PlayRedis) redisTemplate.opsForValue().get(playRedisKey);
    }


    private void sendPuke(List<Puke> pukes, String wxId) {
        StringBuffer sb = new StringBuffer();
        for (Puke puke : pukes) {
            sb.append(PukeUtil.translation(puke.getNum()) + ", ");
        }
        if (sb.isEmpty()) return;

        String rest = sb.toString().substring(0, sb.toString().length() - 2);
        WxUtil.sendMessage(wxId, "您的手牌: " + rest);
    }

}
